<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 淘助跑
-->
<template>
  <div>
    <van-form class="run-up">
      <van-field
        v-model="ruleForm.mobile"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择接单账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(list, index) in accountList" :key="index" center :title="list.nick">
        <template #right-icon>
          <van-switch
            v-model="list.checked"
            active-color="#e4393c"
            size="24"
            @change="onChange(list, index)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import * as run from "@/api/run-up";
export default {
  name: "RunUp",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        mobile: "13567368963",
        password: "19990210"
      },
      IntervalTime: 30,
      type: "qb",
      typeOptions: [{ label: "淘宝任务", type: "qb" }],
      startFlag: false,
      returnContent: [],
      show: false,
      accountList: [],
      accountId: [],
      id: "",
      // 正则
      idRegex: /<option value="(.+?)" >/g,
      guidRegex: /id="hidguid" value="(.+?)"/g,
      nameRegex: /" >(.+?)<\/option>/gi,
      guid: "",
      timer: null,
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 20 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 20 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.mobile = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || "qb";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 20 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.mobile = this.item.user;
      this.ruleForm.password = this.item.pass;
      this.type = this.item.type || "qb";
    }
  },
  methods: {
    // 开始接单
    onStart() {
      const _this = this;
      if (!this.startFlag) {
        // 登录
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        let param = {
          type: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Requested-With": "XMLHttpRequest"
          },
          data: this.ruleForm
        };
        run.ajaxFun(run.getLogin, param, res => {
          _this.returnContent.unshift(alertMsg(res.Message));
          if (res.IsSuccess) {
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.mobile,
              pass: _this.ruleForm.password,
              type: _this.type,
              index: _this.index
            });
            // 获取账号信息
            _this.onGetAccountList(_this);
          } else {
            _this.startFlag = false;
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 获取账号信息
    onGetAccountList(_this) {
      _this.accountList = [];
      _this.accountId = [];
      let param = {
        type: "get",
        dataType: "text",
        data: {}
      };
      run.ajaxFun(run.getAccountList, param, res => {
        let respon = res.replace(/\r\n/g, "");
        _this.guid = respon.match(_this.guidRegex)[0].slice(20, -1);
        if (respon.match(_this.idRegex)) {
          respon.match(_this.idRegex).forEach(item => {
            let id = item.slice(15, -3);
            _this.accountId.push(id);
          });
          respon.match(_this.nameRegex).forEach(item => {
            let nick = item.slice(3, -9);
            _this.accountList.push({
              nick: nick,
              checked: false
            });
          });
          if (_this.accountList.length === 1) {
            // 接单
            _this.returnContent.unshift(
              alertMsg(
                "接单号: " + _this.accountList[0].nick + " 即将开始接单..."
              )
            );
            _this.id = this.accountId[0];
            _this.onGrabSheet();
          } else {
            // 选择账号
            _this.show = true;
          }
        } else {
          _this.$dialog
            .alert({
              title: "提示",
              message: "请先绑定淘宝账户"
            })
            .then(() => {
              _this.startFlag = false;
            });
        }
      });
    },
    // 选择账号
    onChange(list, index) {
      this.show = false;
      this.returnContent.unshift(
        alertMsg("接单号: " + list.nick + " 即将开始接单...")
      );
      this.id = this.accountId[index];
      this.onGrabSheet();
    },
    // 获取html
    onGetHtml() {
      let param = {
        type: "get",
        dataType: "text",
        data: {}
      };
      run.ajaxFun(run.getAccountList, param, () => {
        this.returnContent.unshift(alertMsg("暂无任务，继续接单..."));
        this.onGrabSheet()
      });
    },
    // 抢单
    onGrabSheet() {
      const _this = this;
      _this.returnContent.unshift(alertMsg("暂无任务，继续接单..."));
      clearInterval(this.timer);
      this.$ajax({
        url: "http://www.dk6600.com/wap/tasklist.aspx",
        type: "post",
        dataType: "json",
        ajaxData: {
          values: {
            guid: _this.guid,
            accountId: _this.id ,
            type: _this.type
          }
        },
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: function(res) {
          _this.returnContent.unshift(alertMsg(res.Message));
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetHtml();
              }
            }, _this.IntervalTime * 1000);
          if (res.IsSuccess) {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGrabSheet();
              }
            }, _this.IntervalTime * 1000);
          }
        }
      });
    }
  }
};
</script>
